<template>
  <el-container style="border: solid 1px #5d7db3; margin: 35px;">
    <el-header style="background-color: #5d7db3; display: flex; align-items: center; margin-bottom: 20px;">
      <div class="title">
        <span>稿件管理</span>
      </div>
    </el-header>
    <div class="main-content">
      <el-main>
        <div style="margin-bottom: 10px;">
          <span @mouseenter="showSearchConditions = true" @mouseleave="showSearchConditions = false">
            高级检索
          </span>
          <div class="block" style="margin-bottom: 10px; display: flex; align-items: center;"
            :style="{ display: showSearchConditions ? 'flex' : 'none' }" @mouseenter="showSearchConditions = true"
            @mouseleave="showSearchConditions = true">
            <span>关键字：</span>
            <el-input v-model="input" placeholder="请输入内容" style="width: auto;"></el-input>
            <span class="demonstration">日期:</span>
            <el-date-picker v-model="value" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" style="width: auto;"></el-date-picker>
            <span>栏目：</span>
            <el-select v-model="form.column" placeholder="请选择栏目">
              <el-option v-for="column in columns.data" :key="column.columnId" :label="column.name"
                :value="column.name">
              </el-option>
            </el-select>
            <span>部门：</span>
            <el-select v-model="form.department" placeholder="请选择部门">
              <el-option v-for="department in departments.data" :key="department.departmentId" :label="department.name"
                :value="department.name"></el-option>
            </el-select>
            <div class="button" style="margin-left: 5px;">
              <el-button type="primary"><i class="el-icon-search"></i>搜索</el-button>
            </div>
          </div>
        </div>
        <div>
          <el-tabs type="border-card"  v-model="activeName">
            <!-- 未发布稿件 -->
            <el-tab-pane name="first">
              <template slot="label">
                <i class="el-icon-edit"></i> 未发布稿件
              </template>
              <el-table :data="unpublishedData" border strip style="margin-bottom:20px; width:100%">
                <el-table-column label="日期" :width="timeWidth">
                  <template slot-scope="scope">
                    {{ formatDate(scope.row.subTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="topic" label="新闻标题" :width="contentWidth">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="warning" @click="handleRejectUnpublish(scope.row)">拒稿<i
                        class="el-icon-remove-outline"></i></el-button>
                    <el-button type="primary" @click="handleView(scope.row)">预览<i class="el-icon-view"></i></el-button>
                    <el-button type="success" @click="handleEdit(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
                    <el-button type="danger" @click="handleDeleteUnpublish(scope.row)">删除<i
                        class="el-icon-delete"></i></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination class="Page" @size-change="handleSizeChangeUnpublished"
                @current-change="handleCurrentChangeUnpublished" :current-page="pagination1.page"
                :page-sizes="[10, 20, 30, 50]" :page-size="pagination1.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="pagination1.total"> </el-pagination>
            </el-tab-pane>
            <!-- 已拒绝稿件 -->
            <el-tab-pane name="second">
              <template slot="label">
                <i class="el-icon-circle-close"></i>&nbsp;已拒绝稿件
              </template>
              <el-table :data="rejectedData" border strip style="margin-bottom: 20px;">
                <el-table-column label="日期">
                  <template slot-scope="scope">
                    {{ formatDate(scope.row.subTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="topic" label="新闻标题">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="primary" @click="handleView(scope.row)">预览<i class="el-icon-view"></i></el-button>
                    <el-button type="success" @click="handleEdit(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
                    <el-button type="danger" @click="handleDeleteReject(scope.row)">删除<i
                        class="el-icon-delete"></i></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination class="Page" @size-change="handleSizeChangeRejected"
                @current-change="handleCurrentChangeRejected" :current-page="pagination2.page"
                :page-sizes="[10, 20, 30, 50]" :page-size="pagination2.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="pagination2.total"> </el-pagination>
            </el-tab-pane>
            <!-- 已发布稿件 -->
            <el-tab-pane name="third">
              <template slot="label">
                <i class="el-icon-circle-check"></i>&nbsp;已发布稿件
              </template>
              <el-table :data="publishedData" border strip style="margin-bottom: 20px;">
                <el-table-column label="日期">
                  <template slot-scope="scope">
                    {{ formatDate(scope.row.subTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="topic" label="新闻标题">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="primary" @click="handleView(scope.row)">预览<i class="el-icon-view"></i></el-button>
                    <el-button type="success" @click="handleEdit(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
                    <el-button type="warning" @click="handleUpPublish(scope.row)">置顶<i
                        class="el-icon-top"></i></el-button>
                    <el-button type="danger" @click="handleDeletePublish(scope.row)">删除<i
                        class="el-icon-delete"></i></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination class="Page" @size-change="handleSizeChangePublished"
                @current-change="handleCurrentChangePublished" :current-page="pagination3.page"
                :page-sizes="[10, 20, 30, 50]" :page-size="pagination3.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="pagination3.total"> </el-pagination>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
    </div>
    <el-footer>
    </el-footer>
  </el-container>
</template>

<script>
import axios from 'axios';
export default {
  name: 'MainContent',
  data() {
    return {
      form: {
        department: null, // 初始化为一个对象
        column:'',
      },
      contentWidth: '600px', // 内容列的宽度
      timeWidth: '300px',     // 时间列的宽度
      unpublishedData: [], // "未发布稿件" 
      rejectedData: [], // "已拒绝稿件" 
      publishedData: [], // "已发布稿件" 
      pagination1: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      pagination2: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      pagination3: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      showSearchConditions: false,
      departments: [], // 存放部门列表数据
      columns: [],//存放专栏列表数据
      activeName: 'first',
      input: '',
      value: '',
    };
  },
  mounted() {
    this.fetchUnpublished();
    this.fetchRejected();
    this.fetchPublished();
    this.fetchDepartments();
    this.fetchColumns();
  },
  methods: {
    formatDate(dateTimeString) {
      if (dateTimeString) {
        const parts = dateTimeString.split('T');
        return parts[0];
      }
    },
    //未发布
    handleSizeChangeUnpublished(val) {
      this.pagination1.pageSize = val;
      this.fetchUnpublished();
    },
    handleCurrentChangeUnpublished(val) {
      this.pagination1.page = val;
      this.fetchUnpublished();
    },
    //已拒绝
    handleSizeChangeRejected(val) {
      this.pagination2.pageSize = val;
      this.fetchRejected();
    },
    handleCurrentChangeRejected(val) {
      this.pagination2.page = val;
      this.fetchRejected();
    },
    //已发布
    handleSizeChangePublished(val) {
      this.pagination3.pageSize = val;
      this.fetchPublished();
    },
    handleCurrentChangePublished(val) {
      this.pagination3.page = val;
      this.fetchPublished();
    },
    // 获取部门列表数据的方法
    fetchDepartments() {
      axios.get('/departments/getAll')
        .then(response => {
          if (response.data) {
            console.log('部门数据获取成功:', response.data);
            this.departments = response.data;
          } else {
            console.log('部门数据为空或未成功获取');
          }
        })
        .catch(error => {
          console.error('获取部门数据时出错:', error);
        });
    },
    // 获取专栏列表数据的方法
    fetchColumns() {
      axios.get('/columns/getAll')
        .then(response => {
          if (response.data) {
            console.log('所属专栏数据获取成功:', response.data);
            this.columns = response.data;
          } else {
            console.log('所属专栏数据为空或未成功获取');
          }
        })
        .catch(error => {
          console.error('获取所属专栏数据时出错:', error);
        });
    },
    getDepartmentIdByName(name) {
      // 根据部门名字获取对应的部门 ID
      const department = this.departments.data.find(department => department.name === name);
      return department ? department.departmentId : null;
      // const department = this.departments.forEach(i=> {
      //   i.find(department => department.name === name);
      // })

    },
    //根据栏目名获取栏目id
    getColumnByName(name) {
      const column = this.columns.data.find(column => column.name === name)
      return column ? column.columnId : null;
    },
    //获取未发布稿件数量
    fetchUnpublished() {
      // 使用当前页码和页面大小发送请求  
      axios.post('/article/getAllUnPub', {
        "page": this.pagination1.page, // 使用当前的页码  
        "pageSize": this.pagination1.pageSize // 使用当前的页面大小  
      })
        .then(response => {
          // 检查响应数据的结构  
          console.log("response", response);
          if (response.data && response.data.data && Array.isArray(response.data.data.records)) {
            this.unpublishedData = response.data.data.records;
            // 更新总条数（如果有的话）  
            if (response.data.data.total) {
              this.pagination1.total = response.data.data.total;
            }
          } else {
            console.error('Invalid response format:', response.data);
            this.unpublishedData = [];
          }
        })
        .catch(error => {
          console.error('Error fetching unpublished articles:', error);
          this.unpublishedData = [];
        });
    },
    // 未发布稿件的拒稿按钮
    handleRejectUnpublish(row) {
      console.log('Article ID:', row.articleId);
      axios.put(`/article/refuseArt/${row.articleId}`)
        .then(() => {
          const index = this.unpublishedData.findIndex(item => item.articleId === row.articleId);
          if (index !== -1) {
            this.unpublishedData.splice(index, 1);
            this.rejectedData.push(row);
          } else {
            console.error('Article not found in unpublishedData to reject.');
          }
        })
        .catch(error => {
          console.error('Error rejecting article:', error);
        });
    },
    // 删除未发布稿件
    handleDeleteUnpublish(row) {
      this.$confirm('此操作将永久删除该稿件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求到后端
        axios.delete(`/article/delete/${row.articleId}`)
          .then(() => {
            // 删除成功
            const index = this.unpublishedData.indexOf(row);
            if (index >= 0 && index < this.pagination1.total) {
              this.unpublishedData.splice(index, 1);
              this.fetchUnpublished();
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }
          })
          .catch(error => {
            // 删除失败
            console.error('Error deleting:', error);
            this.$message.error('删除失败，请重试！');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    //获取已拒绝稿件数量
    fetchRejected() {
      // 使用当前页码和页面大小发送请求  
      axios.post('/article/refuseAr', {
        "page": this.pagination2.page, // 使用当前的页码  
        "pageSize": this.pagination2.pageSize // 使用当前的页面大小  
      })
        .then(response => {
          // 检查响应数据的结构  
          console.log("response", response);
          if (response.data && response.data.data && Array.isArray(response.data.data.records)) {
            this.rejectedData = response.data.data.records;
            // 更新总条数（如果有的话）  
            if (response.data.data.total) {
              this.pagination2.total = response.data.data.total;
            }
          } else {
            console.error('Invalid response format:', response.data);
            this.rejectedData = [];
          }
        })
        .catch(error => {
          console.error('Error fetching unpublished articles:', error);
          this.rejectedData = [];
        });
    },
    // 删除已拒绝稿件
    handleDeleteReject(row) {
      this.$confirm('此操作将永久删除该稿件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求到后端
        axios.delete(`/article/delete/${row.articleId}`)
          .then(() => {
            // 删除成功
            const index = this.rejectedData.indexOf(row);
            if (index >= 0 && index < this.pagination2.total) {
              this.rejectedData.splice(index, 1);
              this.fetchRejected();
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }
          })
          .catch(error => {
            // 删除失败
            console.error('Error deleting:', error);
            this.$message.error('删除失败，请重试！');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //获取已发布稿件数量
    fetchPublished() {
      // 使用当前页码和页面大小发送请求  
      axios.post('/article/getAllPub', {
        "page": this.pagination3.page, // 使用当前的页码  
        "pageSize": this.pagination3.pageSize // 使用当前的页面大小  
      })
        .then(response => {
          // 检查响应数据的结构  
          console.log("response", response);
          if (response.data && response.data.data && Array.isArray(response.data.data.records)) {
            this.publishedData = response.data.data.records;
            // 更新总条数（如果有的话）  
            if (response.data.data.total) {
              this.pagination3.total = response.data.data.total;
            }
          } else {
            console.error('Invalid response format:', response.data);
            this.publishedData = [];
          }
        })
        .catch(error => {
          console.error('Error fetching unpublished articles:', error);
          this.publishedData = [];
        });
    },
    // 删除已发布稿件
    handleDeletePublish(row) {
      this.$confirm('此操作将永久删除该稿件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求到后端
        axios.delete(`/article/delete/${row.articleId}`)
          .then(() => {
            // 删除成功
            const index = this.publishedData.indexOf(row);
            if (index >= 0 && index < this.pagination3.total) {
              this.publishedData.splice(index, 1);
              this.fetchPublished();
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }
          })
          .catch(error => {
            // 删除失败
            console.error('Error deleting:', error);
            this.$message.error('删除失败，请重试！');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //稿件编辑
    handleEdit(row) {
      const articleId = row.articleId;
      this.$router.push({ name: 'EditArticle', params: { articleId } });
    },
    //预览
    handleView(row) {
      const articleId = row.articleId;
      this.$router.push({ name: 'ViewArticle', params: { articleId } })
    },
    //置顶
    handleUpPublish(row) {   
      axios.put('/article/1/top', { id: row.articleId }) // 假设的API端点  
        .then(() => {  
          row.top = '1';  
          // 提示用户或执行其他操作  
          alert('稿件已置顶！');  
        })  
        .catch(error => {  
          // 处理错误  
          console.error('Failed to update top status:', error);  
          // 可以在这里给用户显示一个错误消息  
        });  
    },  
  }
}
</script>

<style scoped>
.title {
  font-size: 30px;
  font-family: 500;
  color: aliceblue;
}
</style>
